<template>
  <div class="app-container farming-container">
    <!-- 顶部天气信息 -->
    <div class="weather-panel">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span><i class="el-icon-sunny"></i> 当地天气</span>
          </div>
        </template>
        <div v-if="weather" class="weather-info">
          <div class="weather-main">
            <span class="temperature">{{ weather.temperature }}°C</span>
            <span class="weather-desc">{{ weather.description }}</span>
          </div>
          <div class="weather-details">
            <div class="weather-item">
              <span>湿度: {{ weather.humidity }}%</span>
            </div>
            <div class="weather-item">
              <span>风速: {{ weather.windSpeed }} km/h</span>
            </div>
          </div>
        </div>
        <div v-else class="weather-loading">
          <el-skeleton :rows="3" animated />
        </div>
      </el-card>
    </div>

    <div class="main-content">
      <!-- 左侧种子仓库 -->
      <div class="seed-panel">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span><i class="el-icon-shopping-bag-1"></i> 我的种子</span>
              <el-button type="text" @click="openSeedStore">购买种子</el-button>
            </div>
          </template>
          <div class="seed-list">
            <el-empty v-if="userCrops.length === 0" description="暂无种子，请先购买" />
            <div v-else class="seed-grid">
              <div 
                v-for="crop in userCrops" 
                :key="crop.cropId" 
                class="seed-item"
                @click="selectSeed(crop)"
                :class="{ 'active': selectedSeed && selectedSeed.cropId === crop.cropId }"
              >
                <div class="seed-icon">
                  <img :src="getSeedIcon(crop.cropId)" alt="种子图标">
                </div>
                <div class="seed-info">
                  <div class="seed-name">{{ crop.cropName }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 中间田地区域 -->
      <div class="garden-panel">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span><i class="el-icon-s-grid"></i> 我的田地</span>
            </div>
          </template>
          <div class="garden-grid">
            <!-- 4x4田地网格 -->
            <div 
              v-for="tenancy in tenancies" 
              :key="tenancy.tenancyId" 
              class="garden-plot"
              :class="{
                'plot-empty': tenancy.tenancyStatus === 0,
                'plot-planted': tenancy.tenancyStatus === 1,
                'selected': currentTenancy && currentTenancy.tenancyId === tenancy.tenancyId
              }"
              @click="selectPlot(tenancy)"
            >
              <!-- 空地 -->
              <template v-if="tenancy.tenancyStatus === 0">
                <div class="plot-empty-icon">
                  <i class="el-icon-plus"></i>
                  <span>点击种植</span>
                </div>
              </template>
              
              <!-- 已种植 -->
              <template v-else-if="tenancy.tenancyStatus === 1 && tenancy.crops && tenancy.crops.length > 0">
                <div class="plot-crop">
                  <!-- 根据生长状态显示不同图标 -->
                  <div class="crop-icon" :class="'growth-stage-' + tenancy.crops[0].states">
                    <img :src="getCropIcon(tenancy.crops[0].cropId, tenancy.crops[0].states)" alt="作物图标">
                  </div>
                  <div class="crop-info">
                    <span class="crop-name">{{ tenancy.crops[0].cropName }}</span>
                    <span class="crop-status">{{ getCropStatusText(tenancy.crops[0].states) }}</span>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧好友聊天 -->
      <div class="chat-panel">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span><i class="el-icon-chat-dot-round"></i> 好友聊天</span>
              <el-button type="text" @click="openAddFriend">添加好友</el-button>
            </div>
          </template>
          <div class="chat-container">
            <!-- 好友列表 -->
            <div class="friend-list">
              <el-empty v-if="friends.length === 0" description="暂无好友" />
              <div v-else>
                <div 
                  v-for="friend in friends" 
                  :key="friend.userId" 
                  class="friend-item"
                  :class="{ 'active': currentFriend && currentFriend.userId === friend.userId }"
                  @click="selectFriend(friend)"
                >
                  <div class="friend-avatar">
                    <el-avatar :size="40" :src="friend.avatar || defaultAvatar"></el-avatar>
                  </div>
                  <div class="friend-info">
                    <div class="friend-name">{{ friend.name }}</div>
                    <div class="friend-status" :class="friend.status === 1 ? 'online' : 'offline'">
                      {{ friend.status === 1 ? '在线' : '离线' }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 聊天区域 -->
            <div class="chat-area" v-if="currentFriend">
              <div class="chat-messages" ref="chatMessages">
                <el-empty v-if="chatHistory.length === 0" description="暂无聊天记录" />
                <div v-else>
                  <div 
                    v-for="(message, index) in chatHistory" 
                    :key="index" 
                    class="message-item"
                    :class="{ 'self': message.senderId === userId, 'friend': message.senderId !== userId }"
                  >
                    <div class="message-avatar">
                      <el-avatar 
                        :size="30" 
                        :src="message.senderId === userId ? userAvatar : (currentFriend.avatar || defaultAvatar)">
                      </el-avatar>
                    </div>
                    <div class="message-content">
                      <div class="message-time">{{ formatTime(message.sendTime) }}</div>
                      <div class="message-text">{{ message.content }}</div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 消息输入框 -->
              <div class="chat-input">
                <el-input 
                  v-model="messageInput" 
                  type="textarea" 
                  :rows="2" 
                  placeholder="输入消息..."
                  @keyup.enter.native="sendMessage"
                ></el-input>
                <el-button type="primary" @click="sendMessage">发送</el-button>
              </div>
            </div>
            
            <!-- 未选择好友时的提示 -->
            <div class="no-friend-selected" v-else>
              <el-empty description="请选择一位好友开始聊天" />
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 底部操作面板 -->
    <div class="operation-panel" v-if="currentTenancy && currentTenancy.tenancyStatus === 1">
      <el-card shadow="hover">
        <div class="operation-buttons">
          <el-button type="primary" @click="waterAction" :disabled="!canPerformAction">浇水</el-button>
          <el-button type="success" @click="fertilizeAction" :disabled="!canPerformAction">施肥</el-button>
          <el-button type="warning" @click="weedAction" :disabled="!canPerformAction">除草</el-button>
          <el-button type="danger" @click="deinsectizeAction" :disabled="!canPerformAction">除虫</el-button>
          <el-button type="info" @click="harvestAction" :disabled="!canHarvest">收获</el-button>
        </div>
      </el-card>
    </div>

    <!-- 种子商店对话框 -->
    <el-dialog title="种子商店" v-model="seedStoreVisible" width="60%">
      <div class="seed-store-container">
        <el-table :data="crops" border style="width: 100%">
          <el-table-column prop="cropName" label="作物名称" width="120"></el-table-column>
          <el-table-column prop="cropCycle" label="生长周期(天)" width="120"></el-table-column>
          <el-table-column label="适宜土地" width="120">
            <template #default="scope">
              {{ getGroundTypeText(scope.row.cropGround) }}
            </template>
          </el-table-column>
          <el-table-column prop="cropTemperature" label="适宜温度(°C)" width="120"></el-table-column>
          <el-table-column prop="cropWater" label="需水量" width="100"></el-table-column>
          <el-table-column prop="cropFertilizer" label="需肥量" width="100"></el-table-column>
          <el-table-column prop="cropPrice" label="价格(元)" width="100"></el-table-column>
          <el-table-column prop="cropHabit" label="生长习性" min-width="200"></el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button type="primary" size="small" @click="buySeed(scope.row)">购买</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 添加好友对话框 -->
    <el-dialog title="添加好友" v-model="addFriendVisible" width="30%">
      <el-form :model="friendForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="friendForm.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addFriendVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddFriend">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 播种对话框 -->
    <el-dialog title="选择种子播种" v-model="plantDialogVisible" width="30%">
      <div class="plant-dialog-content">
        <el-empty v-if="userCrops.length === 0" description="暂无种子，请先购买" />
        <div v-else class="seed-selection">
          <div 
            v-for="crop in userCrops" 
            :key="crop.cropId" 
            class="seed-selection-item"
            @click="selectSeedForPlanting(crop)"
            :class="{ 'active': selectedSeedForPlanting && selectedSeedForPlanting.cropId === crop.cropId }"
          >
            <div class="seed-icon">
              <img :src="getSeedIcon(crop.cropId)" alt="种子图标">
            </div>
            <div class="seed-info">
              <div class="seed-name">{{ crop.cropName }}</div>
              <div class="seed-desc">生长周期: {{ crop.cropCycle }}天</div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="plantDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPlant" :disabled="!selectedSeedForPlanting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { useFarmingStore } from '@/stores/farming'

export default {
  name: 'Farming',
  setup() {
    const farmingStore = useFarmingStore()
    const { 
      tenancies,
      currentTenancy,
      crops,
      userCrops,
      weather,
      friends,
      currentFriend,
      chatHistory 
    } = storeToRefs(farmingStore)

    // 从store中获取actions
    const { 
      setCurrentTenancy,
      setCurrentFriend,
      updateTenancy,
      addUserCrop,
      updateCropStatus,
      addFriend,
      addChatMessage
    } = farmingStore

    return {
      tenancies,
      currentTenancy,
      crops,
      userCrops,
      weather,
      friends,
      currentFriend,
      chatHistory,
      setCurrentTenancy,
      setCurrentFriend,
      updateTenancy,
      addUserCrop,
      updateCropStatus,
      addFriend,
      addChatMessage
    }
  },
  setup() {
    const farmingStore = useFarmingStore()
    const { 
      tenancies,
      currentTenancy,
      crops,
      userCrops,
      weather,
      friends,
      currentFriend,
      chatHistory 
    } = storeToRefs(farmingStore)

    // 从store中获取actions
    const { 
      setCurrentTenancy,
      setCurrentFriend,
      updateTenancy,
      addUserCrop,
      updateCropStatus 
    } = farmingStore

    return {
      tenancies,
      currentTenancy,
      crops,
      userCrops,
      weather,
      friends,
      currentFriend,
      chatHistory,
      setCurrentTenancy,
      setCurrentFriend,
      updateTenancy,
      addUserCrop,
      updateCropStatus
    }
  },
  data() {
    return {
      // 用户信息
      userId: null,
      userAvatar: '',
      defaultAvatar: new URL('@/assets/images/profile.jpg', import.meta.url).href,
      
      // 种子相关
      selectedSeed: null,
      seedStoreVisible: false,
      
      // 田地相关
      plantDialogVisible: false,
      selectedSeedForPlanting: null,
      
      // 好友聊天相关
      addFriendVisible: false,
      friendForm: {
        userName: ''
      },
      messageInput: '',
      
      // 图标映射
      cropIcons: {
        // 不同作物在不同生长阶段的图标
        // cropId_state: 'icon-path'
      }
    }
  },
  computed: {
    
    // 判断是否可以执行田地操作（浇水、施肥等）
    canPerformAction() {
      return this.currentTenancy && 
             this.currentTenancy.tenancyStatus === 1 && 
             this.currentTenancy.crops && 
             this.currentTenancy.crops.length > 0 && 
             this.currentTenancy.crops[0].states < 4 // 假设状态4为成熟状态
    },
    
    // 判断是否可以收获
    canHarvest() {
      return this.currentTenancy && 
             this.currentTenancy.tenancyStatus === 1 && 
             this.currentTenancy.crops && 
             this.currentTenancy.crops.length > 0 && 
             this.currentTenancy.crops[0].states === 4 // 假设状态4为成熟状态
    }
  },
  
  created() {
    // 获取用户信息
    this.getUserInfo()
    
    // 获取天气信息
    this.fetchWeather()
    
    // 获取田地信息
    this.fetchTenancies()
    
    // 获取作物信息
    this.fetchCrops()
    
    // 获取用户拥有的作物
    this.fetchUserCrops()
    
    // 获取好友列表
    this.fetchFriends()
    
    // 初始化作物图标
    this.initCropIcons()
  },
  
  methods: {
    
    // 获取用户信息
    async getUserInfo() {
      try {
        // 这里应该调用获取用户信息的API
        // const { data } = await getUserProfile()
        // 模拟数据
        this.userId = '1'
        this.userAvatar = ''
      } catch (error) {
        console.error('获取用户信息失败', error)
      }
    },
    
    // 获取天气信息
    async fetchWeather() {
      try {
        // 这里应该调用获取天气信息的API
        // const { data } = await getWeather()
        // 模拟数据，实际应该从store中获取
        // this.$store.dispatch('farming/fetchWeather')
      } catch (error) {
        console.error('获取天气信息失败', error)
      }
    },
    
    // 获取田地信息
    async fetchTenancies() {
      try {
        // 这里应该调用获取田地信息的API
        // const { data } = await getTenancies()
        // 模拟数据，实际应该从store中获取
        // this.$store.dispatch('farming/fetchTenancies')
      } catch (error) {
        console.error('获取田地信息失败', error)
      }
    },
    
    // 获取作物信息
    async fetchCrops() {
      try {
        // 这里应该调用获取作物信息的API
        // const { data } = await getCrops()
        // 模拟数据，实际应该从store中获取
        // this.$store.dispatch('farming/fetchCrops')
      } catch (error) {
        console.error('获取作物信息失败', error)
      }
    },
    
    // 获取用户拥有的作物
    async fetchUserCrops() {
      try {
        // 这里应该调用获取用户作物的API
        // const { data } = await getUserCrops()
        // 模拟数据，实际应该从store中获取
        // this.$store.dispatch('farming/fetchUserCrops')
      } catch (error) {
        console.error('获取用户作物失败', error)
      }
    },
    
    // 获取好友列表
    async fetchFriends() {
      try {
        // 这里应该调用获取好友列表的API
        // const { data } = await getFriends()
        // 模拟数据，实际应该从store中获取
        // this.$store.dispatch('farming/fetchFriends')
      } catch (error) {
        console.error('获取好友列表失败', error)
      }
    },
    
    // 初始化作物图标
    initCropIcons() {
      // 这里应该根据实际情况初始化不同作物在不同生长阶段的图标
      this.cropIcons = {
        // 示例：小麦的不同生长阶段
        '1_0': new URL('@/assets/images/crops/wheat_seed.png', import.meta.url).href, // 小麦种子
        '1_1': new URL('@/assets/images/crops/wheat_stage1.png', import.meta.url).href, // 小麦幼苗
        '1_2': new URL('@/assets/images/crops/wheat_stage2.png', import.meta.url).href, // 小麦生长期
        '1_3': new URL('@/assets/images/crops/wheat_stage3.png', import.meta.url).href, // 小麦开花期
        '1_4': new URL('@/assets/images/crops/wheat_mature.png', import.meta.url).href, // 小麦成熟期
        
        // 示例：玉米的不同生长阶段
        '2_0': new URL('@/assets/images/crops/corn_seed.png', import.meta.url).href, // 玉米种子
        '2_1': new URL('@/assets/images/crops/corn_stage1.png', import.meta.url).href, // 玉米幼苗
        '2_2': new URL('@/assets/images/crops/corn_stage2.png', import.meta.url).href, // 玉米生长期
        '2_3': new URL('@/assets/images/crops/corn_stage3.png', import.meta.url).href, // 玉米开花期
        '2_4': new URL('@/assets/images/crops/corn_mature.png', import.meta.url).href  // 玉米成熟期
        
        // 可以根据需要添加更多作物的图标
      }
    },
    
    // 获取种子图标
    getSeedIcon(cropId) {
      // 返回种子图标，这里使用作物的种子阶段图标
      return this.cropIcons[`${cropId}_0`] || new URL('@/assets/images/crops/default_seed.png', import.meta.url).href
    },
    
    // 获取作物图标
    getCropIcon(cropId, state) {
      // 根据作物ID和生长状态返回对应的图标
      return this.cropIcons[`${cropId}_${state}`] || new URL('@/assets/images/crops/default_crop.png', import.meta.url).href
    },
    
    // 获取作物状态文本
    getCropStatusText(state) {
      const statusMap = {
        0: '种子期',
        1: '幼苗期',
        2: '生长期',
        3: '开花期',
        4: '成熟期'
      }
      return statusMap[state] || '未知状态'
    },
    
    // 获取土地类型文本
    getGroundTypeText(groundType) {
      const groundMap = {
        1: '沙质土',
        2: '粘土',
        3: '壤土',
        4: '黑土'
      }
      return groundMap[groundType] || '未知土地'
    },
    
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    },
    
    // 选择种子
    selectSeed(crop) {
      this.selectedSeed = crop
    },
    
    // 选择田地
    selectPlot(tenancy) {
      this.setCurrentTenancy(tenancy)
      
      // 如果是空地，打开播种对话框
      if (tenancy.tenancyStatus === 0) {
        this.plantDialogVisible = true
      }
    },
    
    // 选择好友
    selectFriend(friend) {
      this.setCurrentFriend(friend)
      // 获取与该好友的聊天记录
      this.fetchChatHistory(friend.userId)
    },
    
    // 获取与指定好友的聊天记录
    async fetchChatHistory(friendId) {
      try {
        // 这里应该调用获取聊天记录的API
        // const { data } = await getChatHistory(friendId)
        // 模拟数据，实际应该从store中获取
        // this.$store.dispatch('farming/fetchChatHistory', friendId)
      } catch (error) {
        console.error('获取聊天记录失败', error)
      }
    },
    
    // 打开种子商店
    openSeedStore() {
      this.seedStoreVisible = true
    },
    
    // 打开添加好友对话框
    openAddFriend() {
      this.addFriendVisible = true
    },
    
    // 购买种子
    async buySeed(crop) {
      try {
        // 这里应该调用购买种子的API
        // const { data } = await buySeed(crop.cropId)
        
        // 模拟购买成功
        ElMessage.success('购买成功')
        
        // 添加到用户作物列表
        this.addUserCrop(crop)
        
        // 关闭对话框
        this.seedStoreVisible = false
      } catch (error) {
        ElMessage.error('购买失败：' + error.message)
      }
    },
    
    // 提交添加好友
    async submitAddFriend() {
      if (!this.friendForm.userName) {
        ElMessage.warning('请输入用户名')
        return
      }
      
      try {
        // 这里应该调用添加好友的API
        // const { data } = await addFriend(this.friendForm.userName)
        
        // 模拟添加成功
        const newFriend = {
          userId: Date.now().toString(), // 模拟ID
          name: this.friendForm.userName,
          avatar: '',
          status: 1 // 在线状态
        }
        
        // 添加到好友列表
        this.addFriend(newFriend)
        
        ElMessage.success('添加好友成功')
        
        // 重置表单并关闭对话框
        this.friendForm.userName = ''
        this.addFriendVisible = false
      } catch (error) {
        ElMessage.error('添加好友失败：' + error.message)
      }
    },
    
    // 为播种选择种子
    selectSeedForPlanting(crop) {
      this.selectedSeedForPlanting = crop
    },
    
    // 确认播种
    async confirmPlant() {
      if (!this.currentTenancy || !this.selectedSeedForPlanting) {
        ElMessage.warning('请选择田地和种子')
        return
      }
      
      try {
        // 这里应该调用播种的API
        // const { data } = await plantCrop(this.currentTenancy.tenancyId, this.selectedSeedForPlanting.cropId)
        
        // 模拟播种成功，更新田地状态
        const updatedTenancy = {
          ...this.currentTenancy,
          tenancyStatus: 1,
          crops: [
            {
              cropId: this.selectedSeedForPlanting.cropId,
              cropName: this.selectedSeedForPlanting.cropName,
              states: 0, // 初始状态为种子期
              plantTime: new Date().getTime()
            }
          ]
        }
        
        // 更新田地信息
        this.updateTenancy(updatedTenancy)
        
        // 设置当前选中的田地
        this.setCurrentTenancy(updatedTenancy)
        
        ElMessage.success('播种成功')
        
        // 关闭对话框并重置选择
        this.plantDialogVisible = false
        this.selectedSeedForPlanting = null
      } catch (error) {
        ElMessage.error('播种失败：' + error.message)
      }
    },
    
    // 浇水操作
    async waterAction() {
      if (!this.canPerformAction) return
      
      try {
        // 这里应该调用浇水的API
        // const { data } = await waterCrop(this.currentTenancy.tenancyId)
        
        // 模拟浇水成功
        ElMessage.success('浇水成功')
        
        // 更新作物状态，这里简单模拟一下，实际应该根据后端返回的数据更新
        this.updateCropStatus()
      } catch (error) {
        ElMessage.error('浇水失败：' + error.message)
      }
    },
    
    // 施肥操作
    async fertilizeAction() {
      if (!this.canPerformAction) return
      
      try {
        // 这里应该调用施肥的API
        // const { data } = await fertilizeCrop(this.currentTenancy.tenancyId)
        
        // 模拟施肥成功
        ElMessage.success('施肥成功')
        
        // 更新作物状态
        this.updateCropStatus()
      } catch (error) {
        ElMessage.error('施肥失败：' + error.message)
      }
    },
    
    // 除草操作
    async weedAction() {
      if (!this.canPerformAction) return
      
      try {
        // 这里应该调用除草的API
        // const { data } = await weedCrop(this.currentTenancy.tenancyId)
        
        // 模拟除草成功
        ElMessage.success('除草成功')
        
        // 更新作物状态
        this.updateCropStatus()
      } catch (error) {
        ElMessage.error('除草失败：' + error.message)
      }
    },
    
    // 除虫操作
    async deinsectizeAction() {
      if (!this.canPerformAction) return
      
      try {
        // 这里应该调用除虫的API
        // const { data } = await deinsectizeCrop(this.currentTenancy.tenancyId)
        
        // 模拟除虫成功
        ElMessage.success('除虫成功')
        
        // 更新作物状态
        this.updateCropStatus()
      } catch (error) {
        ElMessage.error('除虫失败：' + error.message)
      }
    },
    
    // 收获操作
    async harvestAction() {
      if (!this.canHarvest) return
      
      try {
        // 这里应该调用收获的API
        // const { data } = await harvestCrop(this.currentTenancy.tenancyId)
        
        // 模拟收获成功
        ElMessage.success('收获成功，获得了丰收的喜悦！')
        
        // 更新田地状态为空地
        const updatedTenancy = {
          ...this.currentTenancy,
          tenancyStatus: 0,
          crops: []
        }
        
        // 更新田地信息
        this.updateTenancy(updatedTenancy)
        
        // 设置当前选中的田地
        this.setCurrentTenancy(updatedTenancy)
      } catch (error) {
        ElMessage.error('收获失败：' + error.message)
      }
    },
    
    // 更新作物状态（模拟生长）
    updateCropStatus() {
      if (!this.currentTenancy || !this.currentTenancy.crops || this.currentTenancy.crops.length === 0) return
      
      // 获取当前作物
      const crop = this.currentTenancy.crops[0]
      
      // 如果已经成熟，则不再更新
      if (crop.states >= 4) return
      
      // 模拟作物生长，增加生长状态
      // 实际应该根据后端返回的数据更新
      const newState = Math.min(crop.states + 1, 4)
      
      // 更新作物状态
      const updatedTenancy = {
        ...this.currentTenancy,
        crops: [
          {
            ...crop,
            states: newState
          }
        ]
      }
      
      // 更新田地信息
      this.updateTenancy(updatedTenancy)
      
      // 设置当前选中的田地
      this.setCurrentTenancy(updatedTenancy)
      
      // 如果作物成熟，提示用户
      if (newState === 4) {
        ElMessage.success('作物已成熟，可以收获了！')
      }
    },
    
    // 发送消息
    async sendMessage() {
      if (!this.messageInput.trim() || !this.currentFriend) return
      
      try {
        const message = {
          senderId: this.userId,
          receiverId: this.currentFriend.userId,
          content: this.messageInput.trim(),
          sendTime: new Date().getTime()
        }
        
        // 这里应该调用发送消息的API
        // const { data } = await sendMessage(message)
        
        // 添加消息到聊天记录
        this.addChatMessage(message)
        
        // 清空输入框
        this.messageInput = ''
        
        // 滚动到底部
        this.$nextTick(() => {
          if (this.$refs.chatMessages) {
            this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight
          }
        })
      } catch (error) {
        ElMessage.error('发送消息失败：' + error.message)
      }
    }
  }
}
</script>

<style scoped>
.farming-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  height: calc(100vh - 120px);
  overflow: hidden;
}

.weather-panel {
  width: 100%;
}

.weather-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.weather-main {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.temperature {
  font-size: 24px;
  font-weight: bold;
}

.weather-desc {
  font-size: 16px;
  color: #666;
}

.weather-details {
  display: flex;
  gap: 20px;
}

.main-content {
  display: flex;
  gap: 20px;
  flex: 1;
  overflow: hidden;
}

.seed-panel, .chat-panel {
  width: 25%;
  overflow: auto;
}

.garden-panel {
  flex: 1;
  overflow: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.seed-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.seed-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.seed-item:hover, .seed-item.active {
  background-color: #f0f9eb;
  border-color: #67c23a;
}

.seed-icon img {
  width: 40px;
  height: 40px;
  object-fit: contain;
}

.garden-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(4, 1fr);
  gap: 10px;
  height: 100%;
  min-height: 400px;
}

.garden-plot {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  min-height: 100px;
}

.garden-plot:hover {
  border-color: #409eff;
}

.garden-plot.selected {
  border: 2px solid #409eff;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}

.plot-empty {
  background-color: #f5f7fa;
}

.plot-planted {
  background-color: #f0f9eb;
}

.plot-empty-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.plot-crop {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 100%;
  padding: 10px;
}

.crop-icon {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.crop-icon img {
  max-width: 100%;
  max-height: 60px;
  object-fit: contain;
}

.crop-info {
  text-align: center;
  margin-top: 5px;
}

.crop-name {
  font-weight: bold;
  font-size: 14px;
}

.crop-status {
  font-size: 12px;
  color: #67c23a;
}

.friend-list {
  border-right: 1px solid #ebeef5;
  overflow-y: auto;
  max-height: 300px;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 10px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.friend-item:hover, .friend-item.active {
  background-color: #f5f7fa;
}

.friend-avatar {
  margin-right: 10px;
}

.friend-info {
  flex: 1;
}

.friend-name {
  font-weight: bold;
}

.friend-status {
  font-size: 12px;
}

.friend-status.online {
  color: #67c23a;
}

.friend-status.offline {
  color: #909399;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 300px;
}

.chat-area {
  display: flex;
  flex-direction: column;
  flex: 1;
  padding: 10px;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  margin-bottom: 10px;
}

.message-item {
  display: flex;
  margin-bottom: 15px;
  max-width: 80%;
}

.message-item.self {
  flex-direction: row-reverse;
  align-self: flex-end;
}

.message-avatar {
  margin: 0 10px;
}

.message-content {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  position: relative;
}

.message-item.self .message-content {
  background-color: #ecf5ff;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.chat-input {
  display: flex;
  gap: 10px;
  margin-top: auto;
}

.operation-panel {
  margin-top: 20px;
}

.operation-buttons {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  gap: 10px;
}

.seed-store-container {
  max-height: 500px;
  overflow-y: auto;
}

.seed-selection {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
}

.seed-selection-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.seed-selection-item:hover, .seed-selection-item.active {
  background-color: #f0f9eb;
  border-color: #67c23a;
}

.seed-selection-item .seed-icon img {
  width: 50px;
  height: 50px;
  object-fit: contain;
}

.seed-selection-item .seed-info {
  text-align: center;
  margin-top: 10px;
}

.seed-selection-item .seed-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.seed-selection-item .seed-desc {
  font-size: 12px;
  color: #909399;
}

/* 生长阶段样式 */
.growth-stage-0 img { /* 种子期 */
  transform: scale(0.6);
}

.growth-stage-1 img { /* 幼苗期 */
  transform: scale(0.7);
}

.growth-stage-2 img { /* 生长期 */
  transform: scale(0.8);
}

.growth-stage-3 img { /* 开花期 */
  transform: scale(0.9);
}

.growth-stage-4 img { /* 成熟期 */
  transform: scale(1);
}
</style>
    